package com.yh.rent.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yh.rent.biz.impl.UserBizImpl;
import com.yh.rent.entity.User;

/**
 * Servlet implementation class UserServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";
		request.setAttribute("basePath", basePath);
		String username = request.getParameter("name");
		if (username == null || "".equals(username)) {
			request.getRequestDispatcher("/WEB-INF/templates/login.ftl").forward(request, response);
			return;
		}
		String pwd = request.getParameter("password");
		String error = null;
		String code = request.getParameter("veryCode");
		String rcode = (String) session.getAttribute("rand");
		List<User> users = new UserBizImpl().getAllUsers();
		if (rcode != null && rcode.equals(code)) {
			for (User user : users) {
				if (username.equals(user.getName()) && pwd.equals(user.getPassword())) {
					session.setAttribute("username", user.getName());
					session.setAttribute("user", user);
					request.getRequestDispatcher("HouseServlet").forward(request, response);
					return;
				}
			}
			error = "用户名或密码错误";
		} else {
			error = "验证码错误";
		}
		session.setAttribute("username", username);
		request.setAttribute("error", error);
		request.getRequestDispatcher("/WEB-INF/templates/login.ftl").forward(request, response);
	}
}
